﻿using KingsSharp.Common;
using KingsSharp.Common.Data;
using KingsSharp.Common.Extensions;
using KingsSharp.Core;
using KingsSharp.Core.Data;
using CRM.Admin.Contracts.Contract.Sys;
using CRM.Admin.Contracts.Dto.Sys;
using CRM.Admin.Contracts.Model.Sys;
using System;
using System.Linq;

namespace Property.Main.Services.Service.Sys
{
    public partial class DictionaryService : ServiceBase,IDictionaryService
    {
        private readonly IRepository<DictionaryType, Guid> _dictionarytypeRepository;
        private readonly IRepository<Dictionary, Guid> _dictionaryRepository;

        public DictionaryService(IRepository<DictionaryType, Guid> dictionarytypeRepository,
            IRepository<Dictionary, Guid> dictionaryRepository)
            : base(dictionarytypeRepository.UnitOfWork)
        {
            _dictionarytypeRepository = dictionarytypeRepository;
            _dictionaryRepository = dictionaryRepository;
        }

        #region 字典类别
        /// <summary>
        /// 字典类别集合
        /// </summary>
        public IQueryable<DictionaryType> ItemDictionaryType { get { return _dictionarytypeRepository.Entities; } }

        /// <summary>
        /// 以dto为载体添加字典类别
        /// </summary>
        /// <param name="dtos"></param>
        /// <returns></returns>
        public OperationResult AddDictionaryType(params DictionaryTypeDto[] dtos)
        {
            dtos.CheckNotNull("dtos");
            return _dictionarytypeRepository.Insert(dtos, dto =>
            {
                if (dto.Pid.HasValue)
                {
                    if (_dictionarytypeRepository.ExistsCheck(entity => entity.Parent.Id == dto.Pid.Value && entity.Name == dto.Name))
                    {
                        throw new Exception("同类别下“{0}”的字典类别已存在，不能重复添加。".FormatWith(dto.Name));
                    }
                }
                else
                {
                    if (_dictionarytypeRepository.ExistsCheck(entity => entity.Name == dto.Name && entity.Parent == null))
                    {
                        throw new Exception("“{0}”的字典类别已存在，不能重复添加。".FormatWith(dto.Name));
                    }
                }
            }, (dto, entity) => {
                if (dto.Pid.HasValue)
                {
                    DictionaryType dictype = _dictionarytypeRepository.GetByKey(dto.Pid.Value);
                    if (dictype == null)
                    {
                        throw new Exception("要加入的上级字典类别不存在");
                    }
                    entity.Parent = dictype;
                }
                return entity;
            });
        }

        /// <summary>
        /// 以dto为载体编辑字典类别
        /// </summary>
        /// <param name="dtos"></param>
        /// <returns></returns>
        public OperationResult EditDictionaryType(params DictionaryTypeDto[] dtos)
        {
            dtos.CheckNotNull("dtos");
            return _dictionarytypeRepository.Update(dtos, dto =>
            {
                if (dto.Id == null)
                {
                    throw new Exception("传递的dto主键异常，无法更新。");
                }
            });
        }

        /// <summary>
        /// 删除指定id的字典类别
        /// 删除时、同时将删除类别下的字典
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public OperationResult DeleteDictionaryType(params Guid[] ids)
        {
            ids.CheckNotNull("ids");
            _dictionarytypeRepository.UnitOfWork.TransactionEnabled = true;
            _dictionaryRepository.Delete(entity => ids.Contains(entity.Parent.Id));
            var result = _dictionarytypeRepository.Delete(ids);
            _dictionarytypeRepository.UnitOfWork.SaveChanges();
            return result;
        }
        #endregion


        #region 字典信息
        /// <summary>
        /// 字典信息集合
        /// </summary>
        public IQueryable<Dictionary> ItemDictionary { get { return _dictionaryRepository.Entities; } }

        /// <summary>
        /// 以dto为载体添加字典信息
        /// </summary>
        /// <param name="dtos"></param>
        /// <returns></returns>
        public OperationResult AddDictionary(params DictionaryDto[] dtos)
        {
            dtos.CheckNotNull("dtos");
            return _dictionaryRepository.Insert(dtos, dto =>
            {
                if (dto.Pid.HasValue)
                {
                    if (_dictionaryRepository.ExistsCheck(entity => entity.Parent.Id == dto.Pid.Value && entity.Name == dto.Name))
                    {
                        throw new Exception("同类别下“{0}”的字典类别已存在，不能重复添加。".FormatWith(dto.Name));
                    }
                }
                else
                {
                    if (_dictionaryRepository.ExistsCheck(entity => entity.Name == dto.Name && entity.Parent == null))
                    {
                        throw new Exception("“{0}”的字典类别已存在，不能重复添加。".FormatWith(dto.Name));
                    }
                }
            }, (dto, entity) =>
            {
                if (dto.Pid.HasValue)
                {
                    DictionaryType dic = _dictionarytypeRepository.GetByKey(dto.Pid.Value);
                    if (dic == null)
                    {
                        throw new Exception("要加入的上级字典类别不存在");
                    }
                    entity.Parent = dic;
                }
                return entity;
            });
        }

        /// <summary>
        /// 以dto为载体编辑字典信息
        /// </summary>
        /// <param name="dtos"></param>
        /// <returns></returns>
        public OperationResult EditDictionary(params DictionaryDto[] dtos)
        {
            dtos.CheckNotNull("dtos");
            return _dictionaryRepository.Update(dtos, dto =>
            {
                if (dto.Id == null)
                {
                    throw new Exception("传递的dto主键异常，无法更新。");
                }
            });
        }

        /// <summary>
        /// 删除指定id的字典信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public OperationResult DeleteDictionary(params Guid[] ids)
        {
            ids.CheckNotNull("ids");
            return _dictionaryRepository.Delete(ids);
        }
        #endregion
    }
}
